package com.sh.mytool.cv.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.sh.mytool.cv.dao.BasicDao;
import com.sh.mytool.cv.domain.Article;
import com.sh.mytool.cv.domain.Column;
import com.sh.mytool.cv.service.ColumnService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("columnService")
public class ColumnServiceImpl implements ColumnService {

	@Resource(name="basicDao")
	private BasicDao<Column> columnDao;

	@Override
	public Column get(Long id) {
		return columnDao.findById(Column.class, id);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED, readOnly=true)
	public List<Column> list(Long parentId) {
		Column column = columnDao.findById(Column.class, parentId);
		List<Column> result = null;
		if(column != null){
			result = column.getChildren();
		}
		return result;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void insert(Column column, Long parentId) throws Exception {
		Article article = new Article();
		Column parent = columnDao.findById(Column.class, parentId);
		Integer orderNo = this.getChildMaxOrderNo(parent);
		// cascade insert
		column.setParent(parent);
		article.setColumn(column);
		column.setArticle(article);
		column.setOrderno(orderNo + 1);
		columnDao.insert(column);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void update(Column column) throws Exception {
		Column orgColumn = this.get(column.getId());
		orgColumn.setText(column.getText());
		columnDao.update(orgColumn);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void delete(Long id) throws Exception {
		columnDao.deleteById(Column.class, id);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED, readOnly=true)
	private Integer getChildMaxOrderNo(Column parent) throws Exception{
		String jpaSql = "SELECT MAX(c.orderno) FROM Column c WHERE c.parent.id=?";
		Integer result = (Integer)columnDao.getSingleResult(jpaSql, new Object[]{parent.getId()});
		return result == null ? 0 : result;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED, readOnly=true)
	private Integer getChildMinOrderNo(Column parent) throws Exception{
		String jpaSql = "SELECT MIN(c.orderno) FROM Column c WHERE c.parent.id=?";
		Integer result = (Integer)columnDao.getSingleResult(jpaSql, new Object[]{parent.getId()});
		return result == null ? 0 : result;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
    public void move(Long changeId, Long id) throws Exception {
		Column column = this.get(id);
		Column changeColumn = this.get(changeId);
		Integer temp1 = column.getOrderno();
		Integer temp2 = changeColumn.getOrderno();
		column.setOrderno(temp2);
		changeColumn.setOrderno(temp1);
    }
}
